<template>
  <van-nav-bar class="com-navbar" :border="false">
    <template #left>
      <van-icon name="arrow-left" class="icon-left" @click="onClickLeft" />
    </template>

    <template #right>
      <div class="nav-bar-right" @click="show = true">
        <div class="right-title">{{ langTxt }}</div>
        <svg aria-hidden="true" class="right-image svg-icon">
          <use xlink:href="#icon-lang-down"></use>
        </svg>
      </div>
    </template>
  </van-nav-bar>

  <van-popup
    v-model:show="show"
    position="center"
    @click-overlay="show = false"
  >
    <div class="lang-container" @click.stop>
      <div class="lang-head"> {{t("Language")}} </div>
      <div class="lang-content">
        <div
          class="lang-item"
          v-for="item in langList" :key="item.value"
          :class="{'lang-item-active': langKey === item.value}"
          @click="changeLang(item)"
        >
          {{ item.label }}
        </div>
      </div>
    </div>
  </van-popup>
</template>
<script lang="ts" setup>
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { t, i18nScope  } from '@/languages'

const $router = useRouter()

function onClickLeft() {
  $router.back()
}

const show = ref(false)

const langList = [
  { label: t('English'), value: 'en' },
  { label: t('Hindi'), value: 'hi' },
]

const langKey = ref('')
const langTxt = ref('')

onBeforeMount(() => {
  langKey.value = localStorage.getItem('lang') || 'en'

  langTxt.value = langList.find((item) => item.value === langKey.value)?.label ?? ''
})

async function changeLang(item: { label: string; value: string }) {
  localStorage.setItem('lang', item.value)
  await i18nScope.change(item.value) 
  langKey.value = item.value

  langTxt.value = item.label

  show.value = false

  location.reload()
}

</script>
<style lang="scss" scoped>
.com-navbar {
  background: transparent;
}

.nav-bar-right {
  display: flex;
  align-items: center;
}

.nav-bar-right .right-title {
  color: #fff;
}

.nav-bar-right .right-image {
  margin-left: .21333rem;
  width: .42667rem;
  height: .42667rem;
}

.van-popup {
  width: 80%;
  background: #0d111a;
  border-radius: .13333rem;
}

.lang-container {
  padding: .8rem;
}


.lang-container .lang-head {
  text-align: center;
  font-weight: 600;
}

.lang-container .lang-content {
  margin-top: .8rem;
  display: flex;
  flex-direction: column;
  align-content: center;
  align-items: center;
}

.lang-container .lang-content .lang-item {
  width: 5.06667rem;
  height: 1.33333rem;
  line-height: 1.33333rem;
  text-align: center;
  border-radius: .26667rem;
  color: #fff;
  font-weight: 500;
  margin-bottom: .26667rem;
  background-color: #507b97;
}

.lang-container .lang-content .lang-item-active {
  background-color: #042e4d;
}
</style>
